//
//  LogView.swift
//  TLCLockDemo
//
//  Created by run on 2024/7/16.
//

import AlertToast
import CocoaLumberjackSwift
import Combine
import SwiftUI

class LogModel: ObservableObject {
    var subscriptions = Set<AnyCancellable>()
    @Published var logList: [IdentifiableModel<String>] = []

    init() {
        // receiveData()
    }

    fileprivate func receiveData() {
        DDLog.sharedInstance
            .messagePublisher(with: .info)
            .receive(on: DispatchQueue.main)
            .sink { [weak self] log in
                self?.logList.append(IdentifiableModel("[\(log.timestamp.yMdss)] \(log.message)"))
            }.store(in: &subscriptions)
    }

    fileprivate func cancel() {
        subscriptions.removeAll()
    }

    fileprivate func clearAllLogs() {
        logList.removeAll()
    }

    deinit {
        debugPrint("Log Model deinit")
    }
}

struct LogView: View {
    @StateObject var model: LogModel = .init()

    @State var showToast: Bool = false

    var body: some View {
        VStack(spacing: 0) {
            HStack {
                Text("Log:(点击可复制)")
                    .font(.system(size: 12))
                    .lineSpacing(3.0)
                Spacer()
                Button("清除日志") {
                    model.clearAllLogs()
                }.font(.system(size: 14))
            }
            .padding(.horizontal, 20)
            .padding(.vertical, 10)

            List {
                ForEach(model.logList) { message in
                    Text(message.value)
                        .font(.system(size: 12))
                        .lineSpacing(3.0)
                        .lineLimit(100).onTapGesture {
                            UIPasteboard.general.string = message.value
                            showToast = true
                        }
                }
            }.ignoresSafeArea()
        }
        .toast(isPresenting: $showToast) {
            AlertToast(displayMode: .alert, type: .regular, title: "已复制")
        }
        .onAppear {
            model.receiveData()
        }
        .onDisappear {
            model.cancel()
        }
    }
}
